app.controller('searchController',function($scope,searchService){

    //搜索项
    $scope.searchMap = {
        pageNum: 1,
        pageSize: 20,
        keywords: '',
        brand: '',
        category: '',
        price: '',
        spec: {}
    }

    //添加搜索项
    $scope.addSeachItem = function(key,value) {

        //判断是否是品牌或者分类
        if (key == 'brand' || key == 'category' || key == 'price') {
            $scope.searchMap[key] = value;
        }else {
            //规格选项添加搜索， 一个规格对应一个选项
            $scope.searchMap.spec[key] = value;
        }

        //每次添加或删除搜索项进行重新查询
        $scope.search();
    }

    //移除搜索项
    $scope.removeSeachItem = function(key) {

        //判断是否是品牌或者分类
        if (key == 'brand' || key == 'category' || key == 'price') {
            $scope.searchMap[key] = '';
        }else {
            //删除指定规格  TODO: delete语法？
            delete $scope.searchMap.spec[key];
        }

        //每次添加或删除搜索项进行重新查询
        $scope.search();
    }

    //搜索
    $scope.search=function(){

        //每次点击查询，重置页码
        $scope.searchMap.pageNum = 1;

        searchService.search( $scope.searchMap ).success(
            function(response){
                $scope.resultMap=response;//搜索返回的结果
                console.log(response)
            }
        );
    }


    //触底搜索
    $scope.searchByScroll = function () {



        if ($scope.searchMap.pageNum < $scope.resultMap.totalPages) { //判断是否还有下一页

            //页码增加
            $scope.searchMap.pageNum = $scope.searchMap.pageNum + 1;

            console.log("开始查询第："+$scope.searchMap.pageNum+"页");

            //查询
            searchService.search( $scope.searchMap ).success(
                function(response){

                    //将查询到的商品数据拼接到原有的数据中
                    $scope.resultMap.rows = $scope.resultMap.rows.concat(response.rows);

                }
            );

            console.log($scope.resultMap);

        }

    }

    //排序搜索
    $scope.sortSearch = function (sortField ,sortType) {
        $scope.searchMap.sortField = sortField;
        $scope.searchMap.sortType = sortType;
        $scope.search();
    }

    //判断关键字是不是品牌
    $scope.keywordsIsBrand=function(){
        for(var i=0;i<$scope.resultMap.brandList.length;i++){
            if($scope.searchMap.keywords.indexOf($scope.resultMap.brandList[i].text)>=0){//如果包含
                return true;
            }
        }
        return false;
    }

    //设置一个样式选中的数组
    $scope.activeShowArray = ['active','','','','',''];

    //设置样式
    $scope.setActiveShowArray = function(index) {
        //清空别的全部选项
        $scope.activeShowArray = [];

        //指定显示
        $scope.activeShowArray[index] = 'active';
    }

});
